// Package app 需要注册的后台服务
package app

import (
	"cap_client/api"
	"cap_client/daemon/session_notifications"
	"cap_client/global"
	"cap_client/service"
	"context"
	"github.com/sirupsen/logrus"
	"golang.org/x/sync/errgroup"
	"time"
)

type Daemon struct {
	exitFunc context.CancelFunc
}

func NewDaemon() *Daemon {
	return &Daemon{}
}

// Run runs the service and blocks until complete.
func (d *Daemon) Run(parentCtx context.Context) {
	var (
		g   errgroup.Group
		err error
	)
	ctx, cancelFunc := context.WithCancel(parentCtx)
	d.exitFunc = cancelFunc

	err = service.ClientSer.Register()
	if err != nil {
		logrus.Errorf("register service error:[%s]", err.Error())
	}
	// 启动http服务
	g.Go(func() error {
		defer func() {
			logrus.Errorf("http server exit,err:[%s]", err.Error())
		}()
		err = api.StartHttpServer(httpApiPrefix)
		return err
	})

	// 获取客户端ID
	g.Go(func() error {
		defer func() {
			logrus.Debugf("clientId %d", global.ClientId)
		}()
		ticker := time.NewTicker(60 * time.Second)
		defer ticker.Stop()
		for range ticker.C {
			if global.ClientId == 0 {
				err = service.ClientSer.Register()
				if err != nil {
					logrus.Errorf("register service error:[%s]", err.Error())
				} else {
					return nil
				}
			}
		}
		return nil
	})
	// 监听 win 会话状态变化
	g.Go(func() error {
		defer func() {
			logrus.Errorf("监听 win 会话状态变化时发生错误：%s", err)
		}()
		err = session_notifications.Call(ctx)
		logrus.Errorf("session_notifications.Call err: %v", err)
		return err
	})

	g.Go(func() error {
		defer func() {
			logrus.Debug("优雅关闭,协程-已退出")
			cancelFunc()
		}()
		<-ctx.Done()
		return nil //nolint
	})

	err = g.Wait()
	if err != nil {
		logrus.Debugf("shutting down the server: %v", err)
	}

}
